// import { tenantLogin, tenantCheckAgain, logout } from '@/api/user' // mock 数据
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { userContactInfo, tenantLogin, logout, tenantCheckAgain } from '@/api/auth'
// import { resolve } from 'core-js/fn/promise'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PHONE: (state, phone) => {
    state.phone = phone
  },
  SET_EMAIL: (state, email) => {
    state.email = email
  }
}

const actions = {
  // 手机号/邮箱绑定
  userContactInfo({ commit }, registInfo) {
    return new Promise((resolve, reject) => {
      userContactInfo(registInfo).then(res => {
        const userInfo = res.data.userInfo
        const data = {
          roles: userInfo.roles,
          username: userInfo.username,
          phone: userInfo.phone,
          email: userInfo.email
        }
        localStorage.setItem('userInfoData', JSON.stringify(data))
        setToken(res.data.token)
        commit('SET_TOKEN', res.data.token)
        resolve(res)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // 二次验证 登录
  tenantCheckAgain({ commit }, bodyParams) {
    return new Promise((resolve, reject) => {
      tenantCheckAgain(bodyParams).then(res => {
        console.log('二次校验登录结果======》s', res)
        const userInfo = res.data.userInfo
        const data = {
          roles: userInfo.roles,
          username: userInfo.username,
          phone: userInfo.phone,
          email: userInfo.email
        }
        localStorage.setItem('userInfoData', JSON.stringify(data))
        commit('SET_TOKEN', res.data.token)
        setToken(res.data.token)
        resolve(res)
      }).catch(error => {
        reject(error)
        console.log(error)
      })
    })
  },
  // 获取信息
  getRolesInfo({ commit }) {
    const data = JSON.parse(localStorage.getItem('userInfoData'))
    data.roles = []
    data.roles.push('admin')
    var { roles, username, phone, email } = data
    commit('SET_ROLES', roles)
    commit('SET_NAME', username)
    commit('SET_PHONE', phone)
    commit('SET_EMAIL', email)
    return data
  },
  // user login
  login({ commit }, userInfo) {
    console.log(userInfo)
    const { username, password, verifyCode, verifyId } = userInfo
    return new Promise((resolve, reject) => {
      tenantLogin({ username: username.trim(), password: password, verifyCode: verifyCode, verifyId: verifyId }).then(response => {
        console.log('登录login========>', response)
        const { data } = response
        // commit('SET_TOKEN', data.sign)
        const userInfo = response.data.userInfo
        const paramData = {
          roles: userInfo.roles,
          username: userInfo.username,
          phone: userInfo.phone,
          email: userInfo.email
        }
        localStorage.setItem('userInfoData', JSON.stringify(paramData))
        commit('SET_TOKEN', response.data.token)
        setToken(response.data.token)
        localStorage.setItem('ticket', data.ticket)
        // setToken(data.token)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const { data } = response

  //       if (!data) {
  //         reject('Verification failed, please Login again.')
  //       }

  //       const { roles, name, avatar, introduction } = data

  //       // roles must be a non-empty array
  //       if (!roles || roles.length <= 0) {
  //         reject('getInfo: roles must be a non-null array!')
  //       }

  //       commit('SET_ROLES', roles)
  //       commit('SET_NAME', name)
  //       commit('SET_AVATAR', avatar)
  //       commit('SET_INTRODUCTION', introduction)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
